//
//  OAuthViewController.swift
//  weiBo
//
//  Created by mac on 15/12/10.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    //MARK: - 监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true,completion: nil)
    }
    
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '15138952539';" +
             "document.getElementById('passwd').value = 'wxb19940216';"
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    // 设置界面
    override func loadView() {
        view = webView
        // 设置代理
        webView.delegate = self
        
        title = "登录微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
    override func viewDidLoad() {
        //view.backgroundColor = UIColor.whiteColor()
        // 加载页面
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }
}

extension OAuthViewController: UIWebViewDelegate {
    /**
     将要加载请求的代理方法
     
     - parameter webView:        webView
     - parameter request:        将要加载的请求
     - parameter navigationType: navigationType, 页面跳转的方式
     
     - returns: 返回 false 不加载,返回 true 加载
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //目标:如果是百度,就不加载
        //1.判断访问的主机是否是 www.baidu.com
        guard let url = request.URL where url.host == "www.baidu.com" else {
            return true
        }
        
        //2.从百度地址的 url 提取'code='是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
            print("取消授权")
            
            return false
        }
        
        //3.从 query 字符串中提取'code='后面的授权码
        let code = query.substringFromIndex("code=".endIndex)
        print(query)
        print("授权码是" + code)
        
        //4.加载 accessToken
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            //1.判断错误
            if error != nil {
                print("出错了")
                return
            }
            //2.输出结果
            print(result)
            
        }
        
        return false
        
        
    }
}
